package com.lanou.tk.tourism.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.lanou.tk.tourism.R;
import com.lanou.tk.tourism.activity.RecommendRvWeb;
import com.lanou.tk.tourism.adapter.RecommendRvAdapter;
import com.lanou.tk.tourism.adapter.RecommendRvSpAdapter;
import com.lanou.tk.tourism.adapter.RecommendViewPagerAdapter;
import com.lanou.tk.tourism.entity.Discount;
import com.lanou.tk.tourism.entity.RecommendData;
import com.lanou.tk.tourism.entity.RecommendSlide;
import com.lanou.tk.tourism.entity.Subject;
import com.lanou.tk.tourism.tool.GetBitmaps;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 推荐
 * Created by dllo on 15/10/23.
 */
public class RecommendFragment extends Fragment {


    private ImageView rv_Iv_Top, rv_Iv_Left, rv_Iv_Right;
    private ImageView[] image;

    List<RecommendData> recommendDatas = new ArrayList<RecommendData>();

    private ViewPager recommend_viewPager;//广告栏部分
    private RecyclerView recommend_recyclerView;
    private RecyclerView recommend_Rv_tejia;//特价recylerView

    //定义viewPager适配器对象
    private RecommendViewPagerAdapter recommendViewPagerAdapter;
    private RecommendRvAdapter recommendRvAdapter;
    private RecommendRvSpAdapter recommendRvSpAdapter;

    //定义请求队列
    private RequestQueue queue;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recommend, null);


        recommend_viewPager = (ViewPager) v.findViewById(R.id.recommend_titleViewPager);
        recommendViewPagerAdapter = new RecommendViewPagerAdapter(getChildFragmentManager());//构建适配器对象
        recommend_viewPager.setAdapter(recommendViewPagerAdapter);
        recommendViewPagerAdapter.setOnMyItemClickListener(getActivity());

        rv_Iv_Top = (ImageView) v.findViewById(R.id.rv_Iv_Top);
        rv_Iv_Left = (ImageView) v.findViewById(R.id.rv_Iv_Left);
        rv_Iv_Right = (ImageView) v.findViewById(R.id.rv_Iv_Right);
        image = new ImageView[]{rv_Iv_Top, rv_Iv_Left, rv_Iv_Right};


        recommendRvAdapter = new RecommendRvAdapter(getActivity());
        recommend_recyclerView = (RecyclerView) v.findViewById(R.id.recommend_recyclerView);
        RecyclerViewHeader header = (RecyclerViewHeader) v.findViewById(R.id.header);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(v.getContext(), 1);
        recommend_recyclerView.setLayoutManager(gridLayoutManager);
        recommend_recyclerView.setAdapter(recommendRvAdapter);
        header.attachTo(recommend_recyclerView, true);


        recommend_Rv_tejia = (RecyclerView) v.findViewById(R.id.recommend_Rv_tejia);
        recommendRvSpAdapter = new RecommendRvSpAdapter(v.getContext());
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(v.getContext(), 2);
        recommend_Rv_tejia.setLayoutManager(gridLayoutManager1);
        recommend_Rv_tejia.setAdapter(recommendRvSpAdapter);


        recommendRvAdapter.setOnItemClickLitener(
                new RecommendRvAdapter.OnItemClickLitener() {

                    @Override
                    public void onItemClick(View view, int position) {
                        Intent intent = new Intent(getActivity(), RecommendRvWeb.class);
                        intent.putExtra("view_author_url", recommendDatas.get(position).getView_author_url());
                        startActivity(intent);
                        getActivity().finish();

                    }

                    @Override
                    public void onItemLongClick(View view, int position) {

                    }
                }
        );


        initData();
        initDatas();
        initDataes();
        initDataese();
        return v;

    }

    //初始化数据
    private void initData() {
        queue = Volley.newRequestQueue(getActivity());
        //获取最新消息接口
        String url = "http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883753&lon=121.544282&channel=360m";
        //  Log.i("lanou", "---------------------------------");
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject jsonObject = response.getJSONObject("data");
                            JSONArray jsonArray = jsonObject.getJSONArray("slide");
                            Gson gson = new Gson();
                            List<RecommendSlide> recommendSlides = new ArrayList<RecommendSlide>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                String slide = jsonArray.getString(i);
                                RecommendSlide recommendSlide = gson.fromJson(slide, RecommendSlide.class);
                                recommendSlides.add(recommendSlide);
                            }
                            // 数据添加到适配器中
                            recommendViewPagerAdapter.addData(recommendSlides);
                            //  maxItem = recommendSlides.size();
                            //   handler.postDelayed(r,2000);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }

    public void initDatas() {

        //获取最新消息接口
        String url = "http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883682&lon=121.544338&type=index&page=1&count=50";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");
                            Gson gson = new Gson();

                            for (int i = 0; i < jsonArray.length(); i++) {
                                String data = jsonArray.getString(i);
                                RecommendData recommendData = gson.fromJson(data, RecommendData.class);
                                recommendDatas.add(recommendData);

                            }
                            recommendRvAdapter.addData(recommendDatas);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }


    private void initDataes() {
        //获取最新消息接口
        String url = "http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883753&lon=121.544282&channel=360m";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject jsonObject = response.getJSONObject("data");
                            JSONArray jsonArray = jsonObject.getJSONArray("discount");
                            Gson gson = new Gson();
                            List<Discount> discounts = new ArrayList<Discount>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                String slide = jsonArray.getString(i);
                                Discount discount = gson.fromJson(slide, Discount.class);
                                discounts.add(discount);
                            }
                            Log.d("Recommend", "discounts:" + discounts);
                            recommendRvSpAdapter.addDatas(discounts);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }


    private void initDataese() {


        //获取最新消息接口
        String url = "http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868652011023578&track_app_version=6.6&track_app_channel=360m&track_device_info=amoi77_cu_ics2&track_os=Android4.0.4&app_installtime=1441094124336&lat=38.883753&lon=121.544282&channel=360m";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {

                    String str = new String();

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject jsonObject = response.getJSONObject("data");
                            JSONArray jsonArray = jsonObject.getJSONArray("subject");
                            Gson gson = new Gson();
                            List<Subject> subjects = new ArrayList<Subject>();
                            int k = 0;
                            for (int i = 0; i < jsonArray.length(); i++) {
                                String subject = jsonArray.getString(i);
                                Subject subject1 = gson.fromJson(subject, Subject.class);
                                subjects.add(subject1);

                            }
                            Log.i("subjects", "discounts:" + str);

                            // 发现下一站的三张图片
                            if (subjects != null && subjects.size() > 0) {
                                for (Subject subjectResult : subjects) {
                                    str = subjectResult.getPhoto(); //得到需要的图片网址
                                    GetBitmaps.getBitmapRequest(str, image[k]);
                                    k++;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }


}


